#
# std.pl - utility routines for cgi-bin programs
#
# This file is 'require'd by most cgi-bin scripts at Narrabri.
#
# $Id$
# $URL$
#
$hfprefix = "";
$wwwmeta = "";
$wwwbase = "";
$pi = 3.141592653589793;
#$wwwroot = "/var/www/vhosts/www.narrabri.atnf.csiro.au/htdocs/";
$wwwroot = "/var/www/";
$stylesheet = "ca_style.css";

#------------------------------------------------------------------------
# Read all CGI vars into an associative array.
# If multiple input fields have the same name, they are concatenated into
#   one array element and delimited with the \0 character (which fails if
#   the input has any \0 characters, very unlikely but conceivably possible).
# This is a simple version, that assumes a request method of GET.
sub getcgivars {
    local(%in) ;
    local($name, $value) ;
  
    # Resolve and unencode name/value pairs into %in
    foreach (split('&', $ENV{'QUERY_STRING'})) {
        s/\+/ /g ;
        ($name, $value)= split('=', $_, 2) ;
        $name=~ s/%(..)/chr(hex($1))/ge ;
        $value=~ s/%(..)/chr(hex($1))/ge ;
        $in{$name}.= "\0" if defined($in{$name}) ;  # concatenate multiple vars
        $in{$name}.= $value ;
    }

    return %in ;

}   
#------------------------------------------------------------------------
sub meta{
  my($line) = @_;
  $wwwmeta .= "<META " . $line . ">\n";
}
sub base{
  my($line) = @_;
  $wwwbase = "<BASE HREF=\"" . $line . "\">\n";
}
#------------------------------------------------------------------------
sub observatory{
  my($obs) = @_;
  if($obs eq "mopra"){$hfprefix = "mopra_"; $stylesheet = "mopra_style.css"}
}
#------------------------------------------------------------------------
sub header{
  my($title) = @_;
  print "Content-type: text/html\n\n<HTML>\n<HEAD>\n";
  if($wwwmeta){print $wwwmeta;}
  print "<TITLE>$title</TITLE>\n<LINK rel=\"stylesheet\" type=\"text/css\" href=\"/stylesheets/$stylesheet\">\n</HEAD>\n<BODY>\n";
  if($wwwbase){print $wwwbase;}

  open IN,("$wwwroot/includefiles/" . $hfprefix . "header-cgi.html") or die "Failed to open header";
  while(<IN>){print "$_";}
  close IN;
  print "\n<CENTER><H1>$title</H1></CENTER>\n";

}
#------------------------------------------------------------------------
sub trailer{
  my($sec,$min,$hour,$mday,$mon,$year) = localtime();
  $mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)[$mon];
  $year += 1900;
  if($min < 10){$min = "0$min";}
  print "<HR NOSHADE>Generated on $mday-$mon-$year at $hour:$min<br>\n";
  open IN,"$wwwroot/includefiles/" . $hfprefix . "footer-cgi.html" or die "Failed to open trailer";
  while(<IN>){print "$_";}
  close IN;
  print "</BODY>\n</HTML>\n";
}

#------------------------------------------------------------------------
sub bug{
  my($message) = @_;
  &header("Error in processing request");
  print "<FONT SIZE=+2>Error in processing request:\n$message</FONT>\n";
  &trailer;
  exit 0;
}


